<?php

/**
 * 产品菜单
 *
 * @author dalei.chen
 */

require_once 'CommonController.php';

class Admin_ProductMenuController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->view->title = "管理中心";
    }

    /**
     * 商家列表
     * 
     * @return void
     */
    public function indexAction()
    {
        $partnerProductModel = new Application_Model_PartnerProduct();
        $partnerModel = new Application_Model_Partner();

        //获取当前页码
        $pageSize = 20;
        $pageNo = intval($this->_request->get('pageNo'));
        if (empty($pageNo)) {
            $pageNo = 1;
        }

        //设置URL模板以及条件
        $urls = array();
        $vars = array();
        $wheres = array();

        $vars['partnerName'] = trim($this->_request->get('partnerName'));
        $vars['code'] = trim($this->_request->get('code'));
        $vars['name'] = trim($this->_request->get('name'));
        $urls = $vars;

        if ($vars['partnerName'] != '') {
            $wheres[] = "`partner`.`name` LIKE '%" . addslashes($vars['partnerName']) . "%'";
        }
        if ($vars['code'] != '') {
            $wheres[] = "`product`.`code` LIKE '%" . addslashes($vars['code']) . "%'";
        }
        if ($vars['name'] != '') {
            $wheres[] = "`product`.`name` LIKE '%" . addslashes($vars['name']) . "%'";
        }

        $urls['pageNo'] = '{page}';
        $urlTemplate = $this->view->projectUrl($urls);

        //获取总页数以及记录
        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';
        $sql = "SELECT `product`.*, `partner`.`name` AS `partnerName` FROM `{$partnerProductModel->getTableName()}` AS `product` LEFT JOIN `{$partnerModel->getTableName()}` AS `partner` ON `product`.`partnerCode` = `partner`.`code` {$where} ORDER BY `product`.`id` DESC";
        $dbPaginator = new Application_Model_DbPaginator($sql, $pageSize, $pageNo);
        $recordCount = $dbPaginator->getRecodCount();

        //获取分页html字符
        Zend_Loader::loadClass('Project_Paginator');
        $paginator = new Project_Paginator($recordCount, $pageSize, $pageNo);
        $paginator->urlTemplateContent = $urlTemplate;

        $rows = $dbPaginator->getRows();

        //分配view(分页处理后的记录集以及分页HTML字符)
        $this->view->pageString = $paginator->getPageString();
        $this->view->rows = $rows;
        $urls['pageNo'] = $pageNo;
        $this->view->pageUrl = $this->view->projectUrl($urls);
        $this->view->vars = $vars;
    }

    /**
     * 菜单列表
     * 
     * @return void
     */
    public function menuAction()
    {
        $menuModel = new Application_Model_Menu();
        $partnerProductModel = new Application_Model_PartnerProduct();
        $productMenuModel = new Application_Model_ProductMenu();
        $productCode = trim($this->_request->get('productCode'));

        $productRows = $partnerProductModel->fetchAll(NULL, "id DESC");
        if ($productCode == '' && count($productRows) > 0) {
            $productCode = $productRows[0]['code'];
        }
        if ($productCode == '') {
            exit($this->view->message('产品编号参数没有传递。', $this->view->productUrl(array('action'=>'index'))));
        }

        /*获取所有权限ID*/
        $productMenuRows = $productMenuModel->fetchAll("`productCode` = '{$productCode}'");
        $productMenuIds = array();
        foreach($productMenuRows as $row) {
            $productMenuIds[] = $row['menuId'];
        }

        $templateContent = file_get_contents(APPLICATION_PATH . '/configs/productMenuTemplate.php');
        $this->view->productCode = $productCode;
        $this->view->productRows = $productRows;
        $currentData = array('productMenuIds'=>$productMenuIds);

        $this->view->listContent = $menuModel->makeChildrenListString(0, $templateContent, $currentData, "`status` = '1' AND `type` = '1'");
    }

    /**
     * 保存菜单
     * 
     * @return void
     */
    public function menuSaveAction()
    {
        $ids = $this->_request->get('selectId') ? $this->_request->get('selectId') : array();
        $productCode = $this->_request->get('productCode');       
        $productMenuModel = new Application_Model_ProductMenu();
        /*获取所有权限ID*/
        $productMenuRows = $productMenuModel->fetchAll("`productCode` = '{$productCode}'");
        $existsMenuIds = array();

        foreach($productMenuRows as $row) {
            $existsMenuIds[] = $row['menuId'];
        }
        $deleteMenuIds = array_diff($existsMenuIds, $ids);
        $insertMenuIds = array_diff($ids, $existsMenuIds);
        if (count($deleteMenuIds) > 0) {
            $productMenuModel->delete("`menuId` IN (". implode(',', $deleteMenuIds) .") AND `productCode` = '{$productCode}'");
        }
        if (count($insertMenuIds) > 0) {
            foreach($insertMenuIds as $menuId) {
                $productMenuModel->insert(array('productCode'=>$productCode, 'menuId'=>$menuId));
            }
        }

        $backUrl = $this->_request->get('backUrl') != NULL ? $this->_request->get('backUrl') : @$_SERVER['HTTP_REFERER'];
        redirect($backUrl);
        exit;
    }

    /**
     * 批量设置-步骤1
     * 
     * @return void
     */
    public function batchSetAction()
    {
        $menuModel = new Application_Model_Menu();
        $partnerProductModel = new Application_Model_PartnerProduct();
        $productMenuModel = new Application_Model_ProductMenu();

        $templateContent = file_get_contents(APPLICATION_PATH . '/configs/productMenuBatchTemplate.php');
        $currentData = array();
        $this->view->listContent = $menuModel->makeChildrenListString(0, $templateContent, $currentData, "`status` = '1' AND `type` = '1'");
    }

    /**
     * 批量设置-步骤2
     * 
     * @return void
     */
    public function batchSetStep2Action()
    {
        $menuModel = new Application_Model_Menu();
        $partnerProductModel = new Application_Model_PartnerProduct();
        $selectId = $this->_request->get('selectId');

        if (empty($selectId)) {
            echo $this->view->message('请至少选择一个菜单。', $this->view->projectUrl(array('action'=>'batch-set'))) ;
            exit;
        }
        $productRows = $partnerProductModel->fetchAll(NULL, "id DESC");
        $this->view->productRows = $productRows;

        $templateContent = file_get_contents(APPLICATION_PATH . '/configs/productMenuBatchStep2Template.php');
        $currentData = array();
        $this->view->listContent = $menuModel->makeChildrenListString(0, $templateContent, $currentData, "`status` = '1' AND `type` = '1' AND `id` IN('". implode('\',\'', $selectId) ."')");
    }

    /**
     * 批量设置-保存
     * 
     * @return void
     */
    public function batchSetSaveAction()
    {
        $menuModel = new Application_Model_Menu();
        $partnerProductModel = new Application_Model_PartnerProduct();
        $productMenuModel = new Application_Model_ProductMenu();
        $roleMenuModel = new Application_Model_RoleMenu();
        $selectId = $this->_request->get('selectId');
        $productCodes = $this->_request->get('productCode');
        $updateOption = $this->_request->get('updateOption');

        if (empty($selectId)) {
            echo $this->view->message('请至少选择一个菜单。', $this->view->projectUrl(array('action'=>'batch-set'))) ;
            exit;
        }
        if (empty($productCodes)) {
            echo $this->view->message('请至少选择一个产品。', $this->view->projectUrl(array('action'=>'batch-set'))) ;
            exit;
        }
        if (!in_array($updateOption, array('insert', 'delete'))) {
            echo $this->view->message('请选择操作。', $this->view->projectUrl(array('action'=>'batch-set'))) ;
            exit;
        }

        //添加指定菜单
        if ($updateOption == 'insert') {
            $allNum = 0;
            $successNum = 0;
            foreach($productCodes as $productCode) {
                foreach($selectId as $menuId) {
                    $allNum++;
                    //如果产品菜单不存在
                    if (!$productMenuModel->isExists($productCode, $menuId)) {
                        $productMenuModel->insert(array('productCode'=>$productCode, 'menuId'=>$menuId));
                        $successNum++;
                    }
                }
                
            }
            echo $this->view->message("共处理{$allNum}个产品菜单，插入成功{$successNum}个。", $this->view->projectUrl(array('action'=>'batch-set'))) ;
            exit;
        }
        //删除指定菜单
        if ($updateOption == 'delete') {
            $allNum = 0;
            $successNum = 0;
            foreach($productCodes as $productCode) {
                foreach($selectId as $menuId) {
                    $allNum++;
                    //如果产品菜单不存在
                    if ($productMenuModel->isExists($productCode, $menuId)) {
                        $productMenuModel->delete("`productCode` = '". addslashes($productCode) ."' AND `menuId` = {$menuId}");
                        $successNum++;
                    }
                }
                
            }
            echo $this->view->message("共处理{$allNum}个产品菜单，删除成功{$successNum}个。", $this->view->projectUrl(array('action'=>'batch-set'))) ;
            exit;
        }
    }
}